const fs = require('fs-extra')
const puppeteer = require('puppeteer')
const args = require('optimist').argv

const resume_url = args._.length ? args._[0] : ''

async function buildHTML() {
  await fs.remove('./dist')

  if (!(resume_url && fs.existsSync(resume_url))) {
    console.log(`The file is missing.`)
    return
  }

  await fs.ensureDir('./dist')

  console.log(`Loading from locale "${resume_url.slice(2)}"`)
  const resume = JSON.parse(fs.readFileSync(resume_url, 'utf-8'))

  console.log('Rendering...')
  const html = await require('./index.js').render(resume, true)
  console.log('Saving file...')
  fs.writeFileSync('./dist/index.html', html, 'utf-8')
  console.log('Done')
  return html
}

async function buildPDF(html) {
  const browser = await puppeteer.launch({ headless: true })
  const page = await browser.newPage();
  console.log('Opening puppeteer...')
  await page.setContent(html, { waitUntil: 'networkidle0' })
  console.log('Generating PDF...')
  const pdf = await page.pdf({
    format: 'A4',
    displayHeaderFooter: false,
    printBackground: true,
    margin: {
      top: '0.4in',
      bottom: '0.4in',
      left: '0.4in',
      right: '0.4in',
    }
  })
  await browser.close()
  console.log('Saving file...')
  fs.writeFileSync('./dist/resume.pdf', pdf)
  console.log('Done')
  return pdf
}

async function buildAll() {
  const html = await buildHTML()
  if (html) {
    await buildPDF(html)
  }
}

buildAll().catch(e => {
  console.error(e)
  process.exit(1)
})
